package com.ugold.common.util.validate;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author xujuan
 * @Description:
 * @Date: create in 2019/4/18
 */
@Slf4j
public class EnumValidatorImpl implements ConstraintValidator<EnumValidator, Object>, Annotation {
	private List<Object> values;

	@Override
	public void initialize(EnumValidator enumValidator) {
		// 类型
		Class<?> enumClass = enumValidator.enumTypeClass();
		if (enumClass == null) {
			return;
		}
		// 被校验的属性
		String checkedField = enumValidator.checkedField();
		if (checkedField == null || checkedField.length() == 0) {
			return;
		}
		// 枚举值
		Object[] objects = enumClass.getEnumConstants();
		if (objects == null || objects.length == 0) {
			return;
		}
		String checkedGetMethodName = String.format("get%s", StringUtils.capitalize(checkedField));
		try {
			Method method = enumClass.getMethod(checkedGetMethodName);
			if (Objects.isNull(method)) {
				throw new Exception(String.format("枚举对象{}缺少字段名为code的字段", enumClass.getName()));
			}
			Object value = null;
			values = new ArrayList<>(objects.length);
			for (Object obj : objects) {
				value = method.invoke(obj);
				values.add(value);
			}
		} catch (Exception e) {
			log.error("处理枚举校验异常,异常信息：" + e.getMessage(), e);
		}
	}

	@Override
	public Class<? extends Annotation> annotationType() {
		return null;
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
		return Objects.isNull(value) || values.contains(value) ? true : false;
	}

}
